#include <QQmlApplicationEngine>
#include <QGuiApplication>
#include <QQmlContext>

#include "controlservice.h"
#include "./beans/setclothstyle.h"
#include "./beans/dealmsgpacket.h"
#include "./beans/imageprovider.h"

ControlService::ControlService(const QGuiApplication* parent)
{
    __initBeans();
    __initRegistBean();
    __initQml(parent);
    __initSlots();
}

ControlService::~ControlService(){
    //*按照顺序释放
    m_qmlEngine = nullptr;
    m_SetClothStyle = nullptr;
    m_MsgControl = nullptr;
    m_ShowImage = nullptr;
}

void ControlService::__initQml(const QGuiApplication* app){
    if(m_qmlEngine){
        const QUrl url(QStringLiteral("qrc:/main.qml"));
        connect(m_qmlEngine.get(), &QQmlApplicationEngine::objectCreated,
                         app, [url](QObject *obj, const QUrl &objUrl) {
            if (!obj && url == objUrl)
                QCoreApplication::exit(-1);
        }, Qt::QueuedConnection);
        m_qmlEngine->load(url);
    }
}

void ControlService::__initBeans()
{
   m_MsgControl = std::make_shared<MsgControl>();
   m_qmlEngine = std::make_shared<QQmlApplicationEngine>();
   m_SetClothStyle = std::make_shared<SetClothStyle>();
   m_ShowImage = std::make_shared<ShowImage>();
}

void ControlService::__initRegistBean(){
   m_qmlEngine.get()->rootContext()->setContextProperty("clothStyleObj",m_SetClothStyle.get());
   m_qmlEngine.get()->rootContext()->setContextProperty("printControl",m_MsgControl.get());
   m_qmlEngine.get()->rootContext()->setContextProperty("showImage",m_ShowImage.get());
   m_qmlEngine.get()->addImageProvider(QLatin1String("imageprovider"), m_ShowImage->getInstance());
}

void ControlService::__initSlots(){
    connect(m_MsgControl.get(),&MsgControl::onAddImage,m_ShowImage.get(),&ShowImage::doAddImage);
}
